package com.cbank.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.jhlabs.image.GaussianFilter;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.resizers.Resizers;
import net.coobird.thumbnailator.resizers.configurations.Antialiasing;

public class ImageUtil {

	private static final Logger LOGGER = Logger.getLogger(ImageUtil.class);

	
	/**
	 * 
	 * @Title: zoom
	 * @Description: 指定大小缩放
	 * @param width
	 * @param height
	 * @param soureSrc
	 * @param toSrc
	 */
	public static void zoom(int width, int height, String sourceSrc,
			String toSrc) {
		try {
			Thumbnails.of(sourceSrc).size(width, height).toFile(toSrc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: zoomScale
	 * @Description: 指定大小缩放
	 * @param scale
	 * @param soureSrc
	 * @param toSrc
	 */
	public static void zoomScale(float scale, String sourceSrc, String toSrc) {
		try {
			Thumbnails.of(sourceSrc).scale(scale).toFile(toSrc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: zoomNoScale
	 * @Description: 不按照比例，指定大小进行缩放
	 * @param width
	 * @param height
	 * @param soureSrc
	 * @param toSrc
	 */
	public static void zoomNoScale(int width, int height, String sourceSrc,
			String toSrc) {
		try {
			Thumbnails.of(sourceSrc).size(width, height).keepAspectRatio(false)
					.toFile(toSrc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: cutForPosition
	 * @Description: 裁剪并压缩图片
	 * @param cutWidth
	 * @param cutHeight
	 * @param width
	 * @param height
	 * @param Positions
	 *            Positions.CENTER,Positions.TOP_LEFT...
	 * @param soureSrc
	 * @param toSrc
	 * @return
	 */
	public static void cutForPosition(int cutWidth, int cutHeight, int width,
			int height, Positions positions, String sourceSrc, String toSrc) {
		try {
			Thumbnails.of(sourceSrc)
					.sourceRegion(positions, cutWidth, cutHeight)
					.size(width, height).keepAspectRatio(false).toFile(toSrc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: cutForPosition
	 * @Description: 裁剪图片
	 * @param cutWidth
	 * @param cutHeight
	 * @param positions
	 * @param sourceSrc
	 * @param toSrc
	 */
	public static void cutForPosition(int cutWidth, int cutHeight,
			Positions positions, String sourceSrc, String toSrc)
			throws IOException {
		try {
			Thumbnails.of(sourceSrc)
					.sourceRegion(positions, cutWidth, cutHeight).scale(1.0f)
					.toFile(toSrc);
		} catch (IOException e) {
			throw e;
		}
	}

	/**
	 * 
	 * @Title: imageFomart
	 * @Description: 输出其他格式的图片
	 * @param width
	 * @param height
	 * @param format
	 * @param soureSrc
	 * @param toSrc
	 */
	public static void imageFomart(int width, int height, String format,
			String sourceSrc, String toSrc) {
		try {
			Thumbnails.of(sourceSrc).size(width, height).outputFormat(format)
					.toFile(toSrc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 高斯模糊
	 * 
	 * @param args
	 */
	public static void gaussianBlurImage(String infile, String outFile) {
		try {
			BufferedInputStream backBIS = new BufferedInputStream(
					new FileInputStream(infile));
			BufferedImage originalImage = ImageIO.read(backBIS);
			int height = originalImage.getHeight();
			int width = originalImage.getWidth();

			BufferedImage thumb = Thumbnails.of(infile)
					.antialiasing(Antialiasing.ON)
					.sourceRegion(Positions.CENTER, width, height)
					.size(width, height).outputQuality(0.5f)
					.resizer(Resizers.BICUBIC).asBufferedImage();

			GaussianFilter gaussian = new GaussianFilter(100);
			BufferedImage blurredthumbnail = gaussian.filter(thumb, null);
			File outputfile = new File(outFile);
			ImageIO.write(blurredthumbnail, "png", outputfile);
		} catch (Exception e) {
			LOGGER.error("GaussianBlurImage error:", e);
		}
	}

	/**
	 * 水印
	 * 
	 * @param args
	 */
	public static void waterMark(String inFile, String waterFile, String outFile) {
		try {
			Thumbnails
					.of(inFile)
					.size(600, 960)
					.watermark(PositionsSelf.TOP_BOTTOM_CENTER,
							ImageIO.read(new File(waterFile)), 0.8f)
					.outputQuality(0.8f).toFile(outFile);
		} catch (Exception e) {
			LOGGER.error("waterMark error:", e);
		}
	}

	/**
	 * 计算文字像素长度
	 * 
	 * @param text
	 * @return
	 */
	private static int getTextLength(String text) {
		int textLength = text.length();
		int length = textLength;
		for (int i = 0; i < textLength; i++) {
			int wordLength = String.valueOf(text.charAt(i)).getBytes().length;
			if (wordLength > 1) {
				length += (wordLength - 1);
			}
		}

		return length % 2 == 0 ? length / 2 : length / 2 + 1;
	}

	public static void pressText(String targetImg, String pressText,
			String fontName, int fontStyle, int fontSize, Color color, int x,
			int y, float alpha) {
		try {
			File file = new File(targetImg);
			Image image = ImageIO.read(file);
			int width = image.getWidth(null);
			int height = image.getHeight(null);

			BufferedImage bufferedImage = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(image, 0, 0, width, height, null);
			g.setFont(new Font(fontName, fontStyle, fontSize));
			g.setColor(color);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
					alpha));

			int width_wi = fontSize * getTextLength(pressText);
			int height_wi = fontSize;

			int widthDiff = width - width_wi;
			int heightDiff = height - height_wi;
			if (x < 0) {
				x = widthDiff / 2;
			} else if (x > widthDiff) {
				x = widthDiff;
			}

			if (y < 0) {
				y = heightDiff / 2;
			} else if (y > heightDiff) {
				y = heightDiff;
			}
			g.drawString(pressText, x, y + height_wi);// 水印文件
			g.dispose();
			ImageIO.write(bufferedImage, "JPEG", file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void addTextToPic(String inFileName, String outFilename,
			String drawStr) {
		// 800*263;
		try {
			LOGGER.info("in:" + inFileName + ",out is:" + outFilename
					+ ",drawstr text :" + drawStr);
			int width = 600;
			int height = 200;
			int fontHeight = 70;
			String drStringLine1 = "";
			String drStringLine2 = "";
			if (drawStr.length() > 8) {
				drStringLine1 = drawStr.substring(0, 8);
				drStringLine2 = drawStr.substring(8);
			} else {
				drStringLine1 = drawStr;
			}

			// //设置透明 start
			BufferedImage buffImg = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D gd = buffImg.createGraphics();
			// 设置透明 start
			buffImg = gd.getDeviceConfiguration().createCompatibleImage(width,
					height, Transparency.TRANSLUCENT);
			gd = buffImg.createGraphics();
			// 设置透明 end
			gd.setFont(new Font("STHeiti", Font.CENTER_BASELINE, fontHeight)); // 设置字体
			gd.setColor(Color.black); // 设置颜色
			// gd.drawRect(0, 0, width - 1, height - 1); //画边框
			// gd.drawString(drawStr,
			// width/2-fontHeight*drawStr.length()/2,fontHeight); //输出文字（中文横向居中）
			
			if (StringUtils.isNotBlank(drStringLine2)) {
				gd.drawString(drStringLine1, 0, fontHeight);
				gd.drawString(drStringLine2, 0, fontHeight * 2 + 10);
				LOGGER.info("1 in:" + inFileName + ",out is:" + outFilename
						+ ",drawstr text :" + drStringLine2 + ",drStringLine1:"
						+ drStringLine1);
			} else {
				gd.drawString(drStringLine1, 0, fontHeight + 30);
				LOGGER.info("2 in:" + inFileName + ",out is:" + outFilename
						+ ",drawstr text :" + drStringLine2 + ",drStringLine1:"
						+ drStringLine1);
			}
			 gd.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

			Thumbnails.of(new File(inFileName)).scale(1f)
					.watermark(Positions.BOTTOM_CENTER, buffImg, 0.9f)
					.toFile(new File(outFilename));
		} catch (Exception e) {
			LOGGER.error("IOException,", e);
		}
	}

	public static void main(String[] args) {
		// String sourceSrc = "/Users/xiaoman/picture/pic/big.jpg";
		// String toSrc = "/Users/xiaoman/picture/pic/big-zoom.jpg";
		// zoomScale(0.25f, sourceSrc, toSrc);
		// zoom(200,200,sourceSrc,toSrc);
		// cutForPosition(400, 400, 200, 200, Positions.CENTER, sourceSrc,
		// toSrc);
		// cutForPosition(300, 300, Positions.CENTER, sourceSrc, toSrc);
		addTextToPic("/opt/8080_tomcat_dashu/webapps/ROOT/assets/images/hello/hello_bg1.png",
				"/opt/8080_tomcat_dashu/webapps/ROOT/assets/images/hello/bg2.png", "我是李冰，我是李冰");
	}
	
	public static void test() {
		// String sourceSrc = "/Users/xiaoman/picture/pic/big.jpg";
		// String toSrc = "/Users/xiaoman/picture/pic/big-zoom.jpg";
		// zoomScale(0.25f, sourceSrc, toSrc);
		// zoom(200,200,sourceSrc,toSrc);
		// cutForPosition(400, 400, 200, 200, Positions.CENTER, sourceSrc,
		// toSrc);
		// cutForPosition(300, 300, Positions.CENTER, sourceSrc, toSrc);
		addTextToPic("/opt/8080_tomcat_dashu/webapps/ROOT/assets/images/hello/hello_bg1.png",
				"/opt/8080_tomcat_dashu/webapps/ROOT/assets/images/hello/bg2.png", "我是李冰，我是李冰");
	}
	
	public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException {
		// 获取底图
		BufferedImage buffImg = ImageIO.read(file);
		// 获取层图
		BufferedImage waterImg = ImageIO.read(waterFile);
		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = buffImg.createGraphics();
		int waterImgWidth = waterImg.getWidth();// 获取层图的宽度
		int waterImgHeight = waterImg.getHeight();// 获取层图的高度
		// 在图形和图像中实现混合和透明效果
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
		// 绘制
		g2d.drawImage(waterImg, x, y, 260, 260, null);
		g2d.dispose();// 释放图形上下文使用的系统资源
		return buffImg;
	}

	/**
	 * 输出水印图片
	 * 
	 * @param buffImg
	 *            图像加水印之后的BufferedImage对象
	 * @param savePath
	 *            图像加水印之后的保存路径
	 */
	public static void generateWaterFile(BufferedImage buffImg, String savePath) {
		int temp = savePath.lastIndexOf(".") + 1;
		try {
			ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}

enum PositionsSelf implements Position {

	TOP_BOTTOM_CENTER() {
		public Point calculate(int enclosingWidth, int enclosingHeight,
				int width, int height, int insetLeft, int insetRight,
				int insetTop, int insetBottom) {
			int x = (enclosingWidth / 2) - (width / 2);
			int y = (enclosingHeight / 2) - (height / 2) - 40;
			return new Point(x, y);
		}
	};

}
